package top.jacktgq.concurrent_utils.aqs;

import top.jacktgq.utils.LogUtils;
import top.jacktgq.utils.Sleeper;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @Author CandyWall
 * @Date 2020/11/4--22:17
 * @Description 测试AQS（AbstractQueuedSynchronizer)：抽象队列同步化器
 */
public class AqsDemo {
    public static void main(String[] args) {
        MyLock lock = new MyLock();
        new Thread(() -> {
            lock.lock();
            /*LogUtils.log("locking...");
            lock.lock();
            //这是不可重入锁，同一个对象再没有释放上一次的锁，是不能锁第二次的
            LogUtils.log("locking...");*/
            try {
                LogUtils.log("AqsDemo", "加锁成功");
                Sleeper.sleep(1);
            } finally {
                LogUtils.log("AqsDemo", "解锁成功");
                lock.unlock();
            }
        }, "t1").start();
        new Thread(() -> {
            lock.lock();
            try {
                LogUtils.log("AqsDemo", "加锁成功");
            } finally {
                LogUtils.log("AqsDemo", "解锁成功");
                lock.unlock();
            }
        }, "t2").start();

    }
}

// 自定义锁（不可重入锁）
class MyLock implements Lock {
    //独占锁同步器类
    class MySync extends AbstractQueuedSynchronizer {
        @Override
        //尝试获得锁
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                //加上了锁，并设置owner为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        //尝试释放锁
        protected boolean tryRelease(int arg) {
            //exclusiveOwnerThread没有使用volatile修饰，
            //在释放锁的时候，进行两步操作，应该让有volatile修饰的state放在前面，可以有写屏障的保护
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        @Override
        //是否持有独占锁
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        //创建条件变量，开辟线程等待休息室
        public Condition newConditon() {
            return new ConditionObject();
        }
    }

    private MySync sync = new MySync();


    @Override
    //加锁（不成功，进入等待队列等待）
    public void lock() {
        sync.acquire(1);
    }

    @Override
    //加锁，可打断
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    //尝试加锁（一次）
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    //尝试加锁，带超时
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    //释放锁
    public void unlock() {
        sync.release(1);
    }

    @Override
    //创建条件变量
    public Condition newCondition() {
        return sync.newConditon();
    }
}


